package cn.itcast.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义全局过滤器实现简单身份认证
 */
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 过滤逻辑处理方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求实例
        ServerHttpRequest request = exchange.getRequest();
        //获取响应实例
        ServerHttpResponse response = exchange.getResponse();
        //获取QueryString请求参数
        MultiValueMap<String, String> queryParams = request.getQueryParams();
        //获取authorization参数
        String authorization = queryParams.getFirst("authorization");
        //判断参数值是否是admin，如果不是，则返回403
        if (!"admin".equals(authorization)){
            response.setStatusCode(HttpStatus.FORBIDDEN);
            return response.setComplete();
        }
        //如果是，放行到下一个过滤器
        return chain.filter(exchange);
    }
}
